package com.jjty.dataGenerator.utils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsRequest1 {
    // 信任管理器实现类，信任所有证书
    private static class MyX509TrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // 信任所有客户端证书
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // 信任所有服务器证书
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    /**
     * 发送HTTP/HTTPS POST请求
     * @param url 请求URL
     * @param param 请求参数
     * @return 响应内容
     */
    public static String sendPost(String url, String param) {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("URL不能为空");
        }

        String result = "";
        HttpURLConnection conn = null;

        try {
            URL realUrl = new URL(url);
            String protocol = realUrl.getProtocol().toLowerCase();

            // 根据协议类型创建不同的连接
            if ("https".equals(protocol)) {
                // 处理HTTPS连接
                HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl.openConnection();

                // 创建信任所有证书的SSL上下文
                TrustManager[] tm = { new MyX509TrustManager() };
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tm, new java.security.SecureRandom());

                httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
                httpsConn.setHostnameVerifier((hostname, session) -> true);

                conn = httpsConn;
            } else if ("http".equals(protocol)) {
                // 处理HTTP连接
                conn = (HttpURLConnection) realUrl.openConnection();
            } else {
                throw new IllegalArgumentException("不支持的协议: " + protocol);
            }

            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            conn.setRequestProperty("Content-Length", String.valueOf(param.getBytes("UTF-8").length));

            // 配置连接
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000); // 连接超时时间
            conn.setReadTimeout(10000);    // 读取超时时间

            // 发送请求参数
            try (OutputStream os = conn.getOutputStream();
                 OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                 BufferedWriter writer = new BufferedWriter(osw)) {
                writer.write(param);
                writer.flush();
            }

            // 获取响应状态码
            int responseCode = conn.getResponseCode();

            // 根据状态码读取响应内容
            InputStream inputStream;
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = conn.getInputStream();
            } else {
                inputStream = conn.getErrorStream();
            }

            // 读取响应内容
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                result = response.toString();
            }

            System.out.println("-----HTTP Response Code-----" + responseCode);
            System.out.println("-----Response Body-----" + result);

        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            System.err.println("SSL初始化错误: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("未知异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 断开连接
            if (conn != null) {
                conn.disconnect();
            }
        }

        return result;
    }
}